﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using WindGoes6.Data;
using WindGoes6.Sys;

namespace QDasTransfer.Transducer
{
	/// <summary>
	/// Excel转换器专用。
	/// </summary>
	public class ExcelConverter : TransducerBase
	{
		public static string cid = "202004";

		/// <summary>
		/// 获得转换器的相关信息用于初始化。
		/// </summary>
		public override void Initialize()
		{
			base.Initialize();


			ConvertBase convert = GetConvertByName(cid);
			string info = convert.GetInfoString();
			if (!string.IsNullOrEmpty(info))
			{
				string[] strs = info.Replace("||", "|").Split('|');
				CompanyName = strs[0];
				VertionInfo = strs[1];
				foreach (var item in strs[2].Split('.'))
					pd.AddExt("." + item);
			}
		}

		/// <summary>
		/// 将转换文件进行处理。
		/// </summary>
		/// <param name="inpath"></param>
		/// <returns></returns>
		public override bool TransferFile(string inpath)
		{
			TransLog log = null;
			try
			{
				// 无后缀的文件名
				string filename = Path.GetFileNameWithoutExtension(inpath);
				string outdir = pd.GetOutDirectory(inpath);
				string outpath = Path.Combine(outdir, filename + ".dfq");
				outpath = ProcessOutputFileNameIfRepeated(outpath);

				// 如果输出路径不存在，则进行创建。 
				if (!Directory.Exists(outdir))
					Directory.CreateDirectory(outdir);
					 
				bool finished = Convert(cid, inpath, outpath).ToLower().Contains("true");
				log = finished ?
					new TransLog(LogType.Success, "文件保存成功。", inpath, outpath) :
					new TransLog(LogType.Fail, "保存失败，原因路径不存在，或者没有写入权限。", inpath, outpath);
				LastOutputDfqFile = finished ? outpath : null;
			}
			catch (Exception ex) { log = new TransLog(LogType.Fail, "EX: " + ex.Message, inpath, "no output."); }
			LogList.Add(log);
			return log.LogType == LogType.Success;
		}

		/// <summary>
		/// 主函数，格式如下：201904 operation args 
		/// </summary>
		/// <param name="args"></param>
		public string Convert(string cid, string input, string output)
		{
			ConvertBase convert = GetConvertByName(cid);
			if (convert == null)
				return "failed";

			return convert.Convert(input, output).ToString(); 
		}

		/// <summary>
		/// 返回格式为：无锡联合汽车电子转换EXCEL转换器||V1.0.2||xls.xlsx
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public ConvertBase GetConvertByName(string name)
		{
			Assembly asm = Assembly.GetExecutingAssembly();
			bool p(Type t) => t.Name.Contains(name);
			Type type = asm.GetTypes().Count(p) > 0 ? asm.GetTypes().First(p) : null;
			return type == null ? null : (ConvertBase)Activator.CreateInstance(type);
		}
	}
}
